<template>
  <el-dialog
    v-model="dialogVisible"
    title="终止任务"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="" prop="terminationReason">
        <el-input
          v-model="formData.terminationReason"
          type="textarea"
          :rows="4"
          placeholder="请输入终止原因"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm">
        确认终止
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { MainTasksApi } from '@/api/oa/maintasks'

defineOptions({ name: 'TerminateTaskDialog' })

const message = useMessage()

interface Props {
  visible: boolean
  taskId?: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)
const formRef = ref()

const formData = reactive({
  terminationReason: ''
})

const formRules = {
  terminationReason: [
    { required: true, message: '请输入终止原因', trigger: 'blur' },
    { min: 1, max: 500, message: '终止原因长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

const handleClose = () => {
  formData.terminationReason = ''
  formRef.value?.resetFields()
  dialogVisible.value = false
}

const handleConfirm = async () => {
  if (!props.taskId) {
    message.error('任务ID不能为空')
    return
  }

  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }

  loading.value = true
  try {
    await MainTasksApi.terminateMainTasks(props.taskId, formData.terminationReason)
    message.success('任务终止成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('终止任务失败:', error)
  } finally {
    loading.value = false
  }
}
</script> 